<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="custom-nav-bar">
      <view class="nav-content">
        <view class="nav-left">
          <image src="/static/logo.png" mode="aspectFit" class="nav-logo"></image>
        </view>
        <view class="nav-title">{{pageTitle}}</view>
        <view class="nav-right">
          <view class="nav-icon">...</view>
        </view>
      </view>
    </view>
    
    <!-- 头部问候语 -->
    <view class="greeting">
      <text class="greeting-text">{{greetingText}} {{userName}}</text>
      <image class="avatar" :src="userAvatar"></image>
    </view>

    <!-- 医生工作概览 -->
    <view v-if="userType === 'doctor'" class="work-overview">
      <view class="overview-title">工作概览</view>
      <view class="overview-stats">
        <view class="stat-item">
          <text class="stat-number">{{ workStats.patientCount }}</text>
          <text class="stat-label">患者总数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ workStats.todayPending }}</text>
          <text class="stat-label">今日待处理</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ workStats.recentAssessments }}</text>
          <text class="stat-label">最近评估</text>
        </view>
      </view>
    </view>

    <!-- 快速操作 -->
    <view v-if="userType === 'doctor'" class="quick-actions">
      <view class="action-title">快速操作</view>
      <view class="action-buttons">
        <button class="action-btn" @click="goToPatients">
          <text class="action-icon">👥</text>
          <text class="action-text">我的患者</text>
        </button>
        <button class="action-btn" @click="goToReports">
          <text class="action-icon">📊</text>
          <text class="action-text">查看报告</text>
        </button>
        <button class="action-btn" @click="addPatient">
          <text class="action-icon">➕</text>
          <text class="action-text">添加患者</text>
        </button>
      </view>
    </view>

    <!-- 量表列表 - 所有用户统一显示 -->
    <view class="scale-list">
      <view class="scale-card" @click="navigateToScale('yiYuLiangBiaoStarter')">
        <text class="scale-title">汉密尔顿抑郁量表</text>
        <view class="scale-icon"></view>
      </view>
      
      <view class="scale-card anxiety" @click="navigateToScale('jiaoLvLiangBiao')">
        <text class="scale-title">汉密尔顿焦虑量表</text>
        <view class="scale-icon"></view>
      </view>
      
      <view class="scale-card mania" @click="navigateToScale('kuangZaoLiangBiao')">
        <text class="scale-title">汉密尔狂躁量表</text>
        <view class="scale-icon"></view>
      </view>
    </view>


  </view>
</template>

<script>
  import { getLoginStatus, saveUserInfo } from '../../utils/auth.js';
  import { getUserInfo } from '../../utils/api/auth.js';
  
  export default {
    data() {
      return {
        // 用户信息
        userName: '用户',
        userAvatar: '/static/logo.png',
        userType: 'patient', // 默认患者类型
        pageTitle: '汉密尔顿心理学量表',
        greetingText: '早上好!',
        // 工作统计数据
        workStats: {
          patientCount: 0,
          todayPending: 0,
          recentAssessments: 0
        }
      }
    },
    onLoad(options) {
      // 页面加载时执行
      console.log('index 页面加载完成，时间戳：', Date.now());
      console.log('页面参数:', options);
      
      // 优先从URL参数获取用户类型
      if (options.userType) {
        this.userType = options.userType;
        console.log('从URL参数获取的用户类型:', this.userType);
      } else {
        // 如果URL没有参数，从登录状态获取
        const loginStatus = getLoginStatus();
        if (loginStatus.userType) {
          this.userType = loginStatus.userType;
          console.log('从登录状态获取的用户类型:', this.userType);
        }
      }
      
      // 获取用户信息
      this.loadUserInfo();
    },
    
    onShow() {
      // 每次页面显示时重新检查用户类型并重新加载用户信息
      this.checkUserType();
      this.loadUserInfo(); // 重新加载最新用户信息
    },
    
    methods: {
      // 检查用户类型
      checkUserType() {
        const loginStatus = getLoginStatus();
        if (loginStatus.userType) {
          this.userType = loginStatus.userType;
          console.log('检查到的用户类型:', this.userType);
          this.updatePageContent();
        }
      },
      
      // 更新页面内容
      updatePageContent() {
        // 所有用户统一显示量表，只需根据时间设置问候语
        this.pageTitle = '汉密尔顿心理学量表';
        
        // 根据时间设置问候语
        const hour = new Date().getHours();
        if (hour < 6) {
          this.greetingText = '凌晨好!';
        } else if (hour < 9) {
          this.greetingText = '早上好!';
        } else if (hour < 12) {
          this.greetingText = '上午好!';
        } else if (hour < 14) {
          this.greetingText = '中午好!';
        } else if (hour < 18) {
          this.greetingText = '下午好!';
        } else if (hour < 22) {
          this.greetingText = '晚上好!';
        } else {
          this.greetingText = '夜深了!';
        }
      },
      
      // 加载用户信息
      async loadUserInfo() {
        try {
          // 先从本地获取登录状态
          const loginStatus = getLoginStatus();
          let userInfo = loginStatus.userInfo || {};
          
          // 从登录状态获取用户类型
          if (loginStatus.userType) {
            this.userType = loginStatus.userType;
          }
          
          console.log('[首页] 当前用户类型:', this.userType);
          console.log('[首页] 本地用户信息:', userInfo);
          
          // 如果是医生，优先从医生接口获取信息
          if (this.userType === 'doctor') {
            try {
              const { getDoctorSelf } = require('../../utils/api/doctor.js');
              const doctorResponse = await getDoctorSelf();
              console.log('[首页] 从医生接口获取信息:', doctorResponse);
              
              if (doctorResponse && doctorResponse.code === 200 && doctorResponse.data) {
                userInfo = { ...userInfo, ...doctorResponse.data };
                saveUserInfo(userInfo);
                console.log('[首页] 已从医生接口更新用户信息');
              }
            } catch (doctorError) {
              console.warn('[首页] 从医生接口获取信息失败:', doctorError);
            }
          }
          
          // 尝试从通用API获取最新用户信息
          try {
            const response = await getUserInfo();
            console.log('[首页] 从通用API获取用户信息:', response);
            
            if (response && response.code === 200 && response.data) {
              userInfo = { ...userInfo, ...response.data };
              // 更新本地存储的用户信息
              saveUserInfo(userInfo);
              console.log('[首页] 已更新本地存储的用户信息');
            }
          } catch (apiError) {
            console.warn('[首页] 从API获取用户信息失败，使用本地缓存:', apiError);
          }
          
          console.log('[首页] 最终用户信息:', userInfo);
          console.log('[首页] real_name:', userInfo.real_name);
          console.log('[首页] wechat_name:', userInfo.wechat_name);
          console.log('[首页] name:', userInfo.name);
          
          // 根据用户类型设置用户名
          if (this.userType === 'patient') {
            // 患者：显示真实姓名
            this.userName = userInfo.real_name || userInfo.wechat_name || userInfo.nickname || '患者';
          } else if (this.userType === 'doctor') {
            // 医生：显示"姓氏+医生"
            const fullName = userInfo.real_name || userInfo.wechat_name || userInfo.name || userInfo.nickname || '';
            console.log('[首页] 医生全名:', fullName);
            
            if (fullName && fullName.length > 0) {
              // 取第一个字（姓氏）+ "医生"
              this.userName = fullName.charAt(0) + '医生';
            } else {
              this.userName = '医生';
            }
            console.log('[首页] 医生显示名称:', this.userName);
          } else {
            // 其他用户（管理员等）
            this.userName = userInfo.wechat_name || userInfo.nickname || userInfo.name || '用户';
          }
          
          // 设置用户头像
          this.userAvatar = userInfo.wechat_avatar || userInfo.avatar_url || '/static/logo.png';
          
          // 更新页面内容
          this.updatePageContent();
          
          // 调试信息，帮助确认获取到的用户信息
          console.log('[首页] 显示的用户名:', this.userName);
          console.log('[首页] 当前用户类型:', this.userType);
          
          // 如果是医生，加载工作统计数据
          if (this.userType === 'doctor') {
            this.loadWorkStats();
          }
        } catch (error) {
          console.error('[首页] 加载用户信息失败:', error);
        }
      },
      
      // 加载工作统计数据
      loadWorkStats() {
        // 模拟数据，实际应该从API获取
        this.workStats = {
          patientCount: 12,
          todayPending: 3,
          recentAssessments: 5
        };
      },
      
      // 快速操作 - 跳转到我的患者 (统一跳转到Tab栏的查看报告页面)
      goToPatients() {
        uni.switchTab({
          url: '/pages/chaKanBaoGao/chaKanBaoGao'
        });
      },
      
      // 快速操作 - 跳转到查看报告
      goToReports() {
        uni.switchTab({
          url: '/pages/chaKanBaoGao/chaKanBaoGao'
        });
      },
      
      // 快速操作 - 添加患者（直接跳转）
      addPatient() {
        console.log('跳转到添加患者页面');
        // 直接跳转到搜索患者页面，不需要多余的弹窗
        const { PageStackManager } = require('../../utils/pageStack.js');
        PageStackManager.smartNavigateWithTabBar('/pages/doctor/searchPatient');
      },
      
      // 导航到对应量表页面
      navigateToScale(scaleType) {
        let path = '';
        switch(scaleType) {
          case 'yiYuLiangBiaoStarter':
            path = '/pages/yiYuLiangBiaoStarter/yiYuLiangBiaoStarter';
            break;
          case 'jiaoLvLiangBiao':
            path = '/pages/jiaoLvLiangBiao/jiaoLvLiangBiao';
            break;
          case 'kuangZaoLiangBiao':
            path = '/pages/kuangZaoLiangBiao/kuangZaoLiangBiao';
            break;
        }
        if (path) {
          uni.navigateTo({
            url: path
          });
        }
      },
      
    }
  }
</script>

<style scoped>
  .container {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
        background: linear-gradient(to bottom, #2DB5A3 0%, #80CBC4 20%, #FFFFFF 80%);
      }
      
      /* 自定义导航栏样式 */
      .custom-nav-bar {
        width: 100%;
        padding-top: 44rpx; /* 适配状态栏高度 */
        background-color: #2DB5A3;
      }
      
      .nav-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 88rpx;
        padding: 0 30rpx;
        box-sizing: border-box;
      }
      
      .nav-left,
      .nav-right {
        width: 80rpx;
        height: 88rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .nav-logo {
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
      }
      
  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  }
      
      .nav-icon {
        font-size: 32rpx;
        color: #333333;
      }

  /* 头部问候语 */
  .greeting {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background-color: transparent;
    border-radius: 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.02);
  }
  .greeting-text {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  }
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
  }

  /* 工作概览样式 */
  .work-overview {
    background: #fff;
    margin: 20rpx;
    padding: 30rpx;
    border-radius: 15rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }

  .overview-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }

  .overview-stats {
    display: flex;
    justify-content: space-around;
  }

  .stat-item {
    text-align: center;
  }

  .stat-number {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #2db5a3;
  }

  .stat-label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-top: 10rpx;
  }

  /* 快速操作样式 */
  .quick-actions {
    background: #fff;
    margin: 20rpx;
    padding: 30rpx;
    border-radius: 15rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }

  .action-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }

  .action-buttons {
    display: flex;
    gap: 20rpx;
  }

  .action-btn {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 30rpx 20rpx;
    background: #f8f9fa;
    border-radius: 10rpx;
    border: 1rpx solid #e9ecef;
    transition: all 0.3s ease;
  }

  .action-btn:active {
    background: #e9ecef;
    transform: scale(0.98);
  }

  .action-icon {
    font-size: 40rpx;
    margin-bottom: 10rpx;
  }

  .action-text {
    font-size: 24rpx;
    color: #666;
  }

.scale-list {
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      padding: 20rpx;
    }
    
    .scale-card {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #fff;
      padding: 30rpx;
      border-radius: 20rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      transition: transform 0.2s;
    }
    
    .scale-card:active {
      transform: scale(0.98);
    }
    
    .scale-card.anxiety {
      background-color: #e6f7ff;
    }
    
    .scale-card.mania {
      background-color: #fff7e6;
    }
    
    .scale-title {
      font-size: 32rpx;
      font-weight: 500;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    }
    
    .scale-icon {
      width: 60rpx;
      height: 60rpx;
      background-color: #f0f0f0;
      border-radius: 50%;
    }

  /* 调整内容区域底部间距 */
  .scale-list {
    margin-bottom: 20rpx;
  }
</style>
